package com.fancy.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fancy.common.dto.response.Result;
import com.fancy.user.dto.request.*;
import com.fancy.user.dto.response.UserManageListResponseVO;
import com.fancy.user.entity.User;
import com.fancy.user.entity.UserExperience;
import com.fancy.user.entity.UserMembership;
import com.fancy.user.entity.MembershipType;
import com.fancy.user.mapper.UserMapper;
import com.fancy.user.mapper.UserExperienceMapper;
import com.fancy.user.mapper.UserMembershipMapper;
import com.fancy.user.mapper.MembershipTypeMapper;
import com.fancy.user.service.UserManageService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@RequiredArgsConstructor
public class UserManageServiceImpl implements UserManageService {

    private final UserMapper userMapper;
    private final UserExperienceMapper userExperienceMapper;
    private final UserMembershipMapper userMembershipMapper;
    private final MembershipTypeMapper membershipTypeMapper;
    private final PasswordEncoder passwordEncoder;

    @Override
    public Result<Page<UserManageListResponseVO>> getUserManageList(
            String keyword, Integer status, String membershipType,
            String startDate, String endDate, int page, int size) {

        // 构建查询条件
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        // 关键词搜索（用户名、邮箱、昵称）
        if (StringUtils.hasText(keyword)) {
            wrapper.and(qw -> qw.like("username", keyword)
                    .or().like("email", keyword)
                    .or().like("nickname", keyword));
        }

        // 用户状态筛选
        if (status != null) {
            wrapper.eq("status", status);
        }

        // 注册时间范围筛选
        if (StringUtils.hasText(startDate)) {
            LocalDateTime start = LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay();
            wrapper.ge("create_time", start);
        }
        if (StringUtils.hasText(endDate)) {
            LocalDateTime end = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atTime(23, 59, 59);
            wrapper.le("create_time", end);
        }

        wrapper.orderByDesc("create_time");

        // 分页查询
        Page<User> userPage = new Page<>(page, size);
        Page<User> resultPage = userMapper.selectPage(userPage, wrapper);

        // 转换为响应DTO
        List<UserManageListResponseVO> responseList = resultPage.getRecords().stream()
                .map(this::convertToUserManageListResponseVO)
                .collect(Collectors.toList());

        // 根据会员类型进行后置筛选
        if (StringUtils.hasText(membershipType)) {
            responseList = responseList.stream()
                    .filter(user -> membershipType.equals(user.getMembershipType()))
                    .collect(Collectors.toList());
        }

        Page<UserManageListResponseVO> responsePage = new Page<>(page, size);
        responsePage.setRecords(responseList);
        responsePage.setTotal(resultPage.getTotal());
        responsePage.setSize(size);
        responsePage.setCurrent(page);

        return Result.success(responsePage);
    }

    @Override
    public Result<Void> manageUser(Long userId, UserManageRequestDTO dto) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.fail("用户不存在");
        }

        // 更新用户状态
        if (dto.getStatus() != null) {
            user.setStatus(dto.getStatus());
        }
        user.setUpdateTime(LocalDateTime.now());

        int result = userMapper.updateById(user);
        if (result <= 0) {
            return Result.fail("管理用户失败");
        }

        // TODO: 记录管理日志

        return Result.success(null);
    }

    @Override
    public Result<Void> deleteUser(Long userId, String deleteReason) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.fail("用户不存在");
        }

        // 软删除：设置状态为删除状态
        user.setStatus(-1); // -1表示已删除
        user.setUpdateTime(LocalDateTime.now());

        int result = userMapper.updateById(user);
        if (result <= 0) {
            return Result.fail("删除用户失败");
        }

        // TODO: 记录删除日志

        return Result.success(null);
    }

    @Override
    public Result<Void> batchDeleteUsers(BatchDeleteUsersRequestDTO dto) {
        if (dto.getUserIds() == null || dto.getUserIds().isEmpty()) {
            return Result.fail("用户ID列表不能为空");
        }

        for (Long userId : dto.getUserIds()) {
            Result<Void> result = deleteUser(userId, dto.getDeleteReason());
            if (!result.isSuccess()) {
                return Result.fail("批量删除失败：" + result.getMessage());
            }
        }

        return Result.success(null);
    }

    @Override
    public Result<Void> resetUserPassword(Long userId, ResetPasswordRequestDTO dto) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.fail("用户不存在");
        }

        // 加密新密码
        String encodedPassword = passwordEncoder.encode(dto.getNewPassword());
        user.setPassword(encodedPassword);
        user.setUpdateTime(LocalDateTime.now());

        int result = userMapper.updateById(user);
        if (result <= 0) {
            return Result.fail("重置密码失败");
        }

        // TODO: 如果设置了强制修改，需要在用户表中添加相应字段

        return Result.success(null);
    }

    @Override
    public Result<Void> setUserMembership(Long userId, SetUserMembershipRequestDTO dto) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.fail("用户不存在");
        }

        // 验证会员类型
        MembershipType membershipType = membershipTypeMapper.selectByTypeCode(dto.getMembershipTypeCode());
        if (membershipType == null) {
            return Result.fail("会员类型不存在");
        }

        // 终止现有会员
        userMembershipMapper.expireUserMembership(userId);

        // 创建新会员记录
        UserMembership userMembership = new UserMembership();
        userMembership.setUserId(userId);
        userMembership.setMembershipTypeId(membershipType.getTypeId());
        userMembership.setStartTime(LocalDateTime.now());
        userMembership.setEndTime(LocalDateTime.now().plusDays(dto.getDurationDays()));
        userMembership.setStatus(1);
        userMembership.setOrderId("ADMIN_SET_" + System.currentTimeMillis()); // 管理员设置的特殊订单号
        userMembership.setCreateTime(LocalDateTime.now());

        int result = userMembershipMapper.insert(userMembership);
        if (result <= 0) {
            return Result.fail("设置会员失败");
        }

        return Result.success(null);
    }

    /**
     * 转换User实体为UserManageListResponseVO
     */
    private UserManageListResponseVO convertToUserManageListResponseVO(User user) {
        UserManageListResponseVO vo = new UserManageListResponseVO();
        BeanUtils.copyProperties(user, vo);

        // 获取用户等级
        UserExperience userExperience = userExperienceMapper.selectOne(
                new QueryWrapper<UserExperience>().eq("user_id", user.getUserId()));
        if (userExperience != null) {
            vo.setCurrentLevel(userExperience.getCurrentLevel());
        }

        // 获取会员类型
        QueryWrapper<UserMembership> membershipWrapper = new QueryWrapper<>();
        membershipWrapper.eq("user_id", user.getUserId())
                .eq("status", 1)
                .gt("end_time", LocalDateTime.now());
        UserMembership userMembership = userMembershipMapper.selectOne(membershipWrapper);

        String membershipTypeCode = "NORMAL"; // 默认普通会员
        if (userMembership != null) {
            MembershipType type = membershipTypeMapper.selectById(userMembership.getMembershipTypeId());
            if (type != null) {
                membershipTypeCode = type.getTypeCode();
            }
        }
        vo.setMembershipType(membershipTypeCode);

        return vo;
    }
}
